#!/usr/bin/env pwsh

Write-Host "=========================================" -ForegroundColor Cyan
Write-Host "用户管理系统启动脚本" -ForegroundColor Cyan
Write-Host "=========================================" -ForegroundColor Cyan

# 检查Go环境
Write-Host "检查Go环境..." -ForegroundColor Green
try {
    $goVersion = go version
    Write-Host "Go环境已安装: $goVersion" -ForegroundColor Green
} catch {
    Write-Host "错误: 未找到Go环境，请先安装Go" -ForegroundColor Red
    exit 1
}

# 检查目录
if (-not (Test-Path "./cmd/main.go")) {
    Write-Host "错误: 找不到项目主文件，请在项目根目录运行脚本" -ForegroundColor Red
    exit 1
}

# 清理旧的构建文件
if (Test-Path "./output") {
    Write-Host "清理旧的构建文件..." -ForegroundColor Green
    Remove-Item -Path "./output" -Recurse -Force
}

# 安装依赖
Write-Host "安装Go依赖..." -ForegroundColor Green
try {
    go mod tidy
    Write-Host "依赖安装成功" -ForegroundColor Green
} catch {
    Write-Host "错误: 依赖安装失败: $_" -ForegroundColor Red
    exit 1
}

# 构建项目
Write-Host "构建项目..." -ForegroundColor Green
mkdir -p output
try {
    go build -o output/user_management_system.exe ./cmd/main.go
    if (Test-Path "./output/user_management_system.exe") {
        Write-Host "项目构建成功!" -ForegroundColor Green
    } else {
        Write-Host "错误: 项目构建失败，可执行文件未生成" -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "错误: 项目构建失败: $_" -ForegroundColor Red
    exit 1
}

# 数据库连接提示
Write-Host "=========================================" -ForegroundColor Yellow
Write-Host "请确保MySQL数据库已启动并且配置正确:" -ForegroundColor Yellow
Write-Host "  - 主机: 127.0.0.1:3308" -ForegroundColor Yellow
Write-Host "  - 用户名: root" -ForegroundColor Yellow
Write-Host "  - 密码: 123456" -ForegroundColor Yellow
Write-Host "  - 数据库名: cruduser" -ForegroundColor Yellow
Write-Host "=========================================" -ForegroundColor Yellow

# 数据库连接检查
Write-Host "\n正在检查数据库连接..." -ForegroundColor Green
try {
    $connectionTest = Invoke-WebRequest -Uri "http://localhost:8900/api/health" -UseBasicParsing -TimeoutSec 5 -ErrorAction Stop
    if ($connectionTest.StatusCode -eq 200) {
        Write-Host "✓ 数据库连接正常" -ForegroundColor Green
    }
} catch {
    Write-Host "✗ 数据库连接失败: $_" -ForegroundColor Red
}

# 启动服务
Write-Host "\n=========================================" -ForegroundColor Cyan
Write-Host "启动用户管理系统服务..." -ForegroundColor Green
Write-Host "=========================================" -ForegroundColor Cyan

# 运行服务
cd output
try {
    ./user_management_system.exe
} catch {
    Write-Host "✗ 服务启动失败: $_" -ForegroundColor Red
}